//
//  CAIErrorSolutionWebController.m
//  CAIEmptyViewKit
//
//  Created by 海参 on 2022/7/4.
//

#import "CAIErrorSolutionWebController.h"
#import "EmptyViewKitTool.h"

@interface CAIErrorSolutionWebController ()<WKNavigationDelegate,WKUIDelegate,UIGestureRecognizerDelegate>

///默认是否隐藏
@property (nonatomic, assign) BOOL defaultWebNavigationBarHide;

@end

@implementation CAIErrorSolutionWebController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    //搭建UI
    self.view.backgroundColor = [UIColor whiteColor];
    //设置导航条
    [self zxwkSetupNav];

    //添加WKWebView；
    [self.view addSubview:self.webView];
    
    //添加进度条
    [self.view addSubview:self.progressView];
     
    [self addConstraint:self.webView toSuperviewItem:self.view];

    //添加监听
    [self zxWkAddObserver];

    if (self.localHtmlFilePath) {
        [self loadHTMLStringWithContentsOfFile:self.localHtmlFilePath];
    }
}

///path:JS所在的路径
- (nullable WKNavigation *)loadHTMLStringWithContentsOfFile:(NSString *)path{
    //根据JS所在的路径,获得html内容
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //加载js
     [self.webView loadHTMLString:html baseURL:nil];
    return nil;
}


-(void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];

}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)dealloc
{
    self.webView.navigationDelegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(title)) ];
    [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(URL)) ];
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
//    if (self.options.statusBarStyle != UIStatusBarStyleLightContent) {
//        if (@available(iOS 13.0, *)) {
//            return UIStatusBarStyleDarkContent;
//        } else {
//            return UIStatusBarStyleDefault;
//        }
//    }
    return UIStatusBarStyleLightContent;
}

//2020.3.10 修改；如果导航条隐藏则置顶显示，如果有导航条则导航条下显示；
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.progressView.frame = CGRectMake(0,[self safeAreaLayoutGuideY], self.view.bounds.size.width, 2);
}

- (CGFloat)safeAreaLayoutGuideY
{
    CGFloat originY = 0;
    if (@available(iOS 11.0, *)) {
        UILayoutGuide *layout = self.view.safeAreaLayoutGuide;
        originY = layout.layoutFrame.origin.y;
    }else
    {
        UILayoutGuide *layout = self.view.layoutMarginsGuide;
        originY = layout.layoutFrame.origin.y;
    }
    return originY;
}



#pragma mark - UI加载



#pragma mark -初始化导航条
- (void)zxwkSetupNav
{
    self.defaultWebNavigationBarHide = self.navigationController.navigationBar.isHidden;
}

#pragma mark -初始化WebView

- (WKWebView *)webView
{
    if (!_webView)
    {
        WKUserContentController *contentController = [[WKUserContentController alloc] init];
        
        //不能乱设置，不然布局会乱
        WKPreferences *preferences = [[WKPreferences alloc] init];
        //默认值
        preferences.minimumFontSize = 0.f;
        preferences.javaScriptEnabled = YES;
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = contentController ;
        configuration.preferences = preferences;
        configuration.allowsInlineMediaPlayback = YES;
        if (@available(iOS 9.0, *))
        {
            configuration.allowsPictureInPictureMediaPlayback = YES;
            configuration.allowsAirPlayForMediaPlayback  = YES;
        }
        if (@available(iOS 10.0, *)) {
            // 音乐自动播放；iOS10
            configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
            //数据链接
            configuration.dataDetectorTypes = !WKDataDetectorTypeAddress;
        } else {
            // ios9
            if ([configuration respondsToSelector:@selector(requiresUserActionForMediaPlayback)])
            {
                configuration.requiresUserActionForMediaPlayback = NO;
            }
        }
        CGFloat top = kHEIGHT_NAV;
        WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0,top, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-top-[EmptyViewKitTool safeAreaLayoutNormalBottom]) configuration:configuration]; //设置frame来调整，用wkWebView.scrollView.contentInset会引起H5底部参考点出错
        wkWebView.backgroundColor = self.view.backgroundColor;
        if (@available(iOS 9.0, *))
        {
            wkWebView.allowsLinkPreview = YES;
        }
        wkWebView.navigationDelegate = self;
        wkWebView.UIDelegate = self;
        _webView = wkWebView;
    }
    return _webView;
}

- (UIProgressView *)progressView
{
    if (!_progressView) {
        UIProgressView *view = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        view.trackTintColor = [UIColor clearColor];
        view.progressTintColor = UIColorFromRGB_HexValue(0xFF5434);
        _progressView = view;
    }
    return _progressView;
}

#pragma mark - constraint

- (void)addConstraint:(UIView *)item toSuperviewItem:(UIView *)superView
{
    item.translatesAutoresizingMaskIntoConstraints = NO;
    if (@available(iOS 11.0, *))         {
        UILayoutGuide *layoutGuide_superView = self.view.safeAreaLayoutGuide;
        NSLayoutConstraint *constraint_top = [item.topAnchor constraintEqualToAnchor:layoutGuide_superView.topAnchor constant:0];
        NSLayoutConstraint *constraint_bottom = [item.bottomAnchor constraintEqualToAnchor:layoutGuide_superView.bottomAnchor constant:0];
        NSLayoutConstraint *constraint_leading = [item.leadingAnchor constraintEqualToAnchor:layoutGuide_superView.leadingAnchor constant:0];
        NSLayoutConstraint *constraint_centerX = [item.centerXAnchor constraintEqualToAnchor:layoutGuide_superView.centerXAnchor];
        [NSLayoutConstraint activateConstraints:@[constraint_top,constraint_bottom,constraint_leading,constraint_centerX]];
    }
    else if([[UIDevice currentDevice] systemVersion].floatValue>=9.f)
    {
        // Fallback on earlier versions
        UILayoutGuide *layoutGuide_superView = self.view.layoutMarginsGuide;
        NSLayoutConstraint *constraint_top = [item.topAnchor constraintEqualToAnchor:layoutGuide_superView.topAnchor constant:0];
        NSLayoutConstraint *constraint_bottom = [item.bottomAnchor constraintEqualToAnchor:layoutGuide_superView.bottomAnchor constant:0];
        NSLayoutConstraint *constraint_leading = [NSLayoutConstraint constraintWithItem:item attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeLeading multiplier:1 constant:0];
        //x的center
        NSLayoutConstraint *constraint_centerX = [NSLayoutConstraint constraintWithItem:item attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
        [NSLayoutConstraint activateConstraints:@[constraint_top,constraint_bottom,constraint_leading,constraint_centerX]];
    }
}


#pragma mark - 添加KVO观察者

// kvo监听，获得页面title和加载进度值;
- (void)zxWkAddObserver
{
    [self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(title)) options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(URL)) options:NSKeyValueObservingOptionNew context:NULL];
    [self.webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark -KVO的监听代理

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //加载进度值
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView)
    {
        NSLog(@"%@",@(self.webView.estimatedProgress));
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.progressView setAlpha:1.0f];
            BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
            if (animated)
            {
                [self.progressView setProgress:self.webView.estimatedProgress animated:animated];
            }
            if(self.webView.estimatedProgress >= 1.0f)
            {
                [UIView animateWithDuration:0.5f delay:0.1f options:UIViewAnimationOptionCurveEaseOut
                                 animations:^{
                                     [self.progressView setAlpha:0.0f];
                                 }completion:^(BOOL finished) {
                                     [self.progressView setProgress:0.0f animated:NO];
                                 }];
            }
        });
    }
    //网页title
    else if ([keyPath isEqualToString:NSStringFromSelector(@selector(title))] && object ==self.webView)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (self.webView.title.length>0)
            {
                self.navigationItem.title = self.webView.title;
            }
        });
    }
    else if ([keyPath isEqualToString:@"canGoBack"] && object == self.webView) {
        // 当前webView是否有h5跳转
        self.webView.allowsBackForwardNavigationGestures = self.webView.canGoBack;
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
